import type { AxiosRequestConfig, AxiosResponse } from 'axios'

export function useRequestLoading() {
  const loadingRef = useState<boolean>('requestLoading', () => false)
  let times = 0
  let loadingToastIns
  return {
    loadingRef,
    withLoadingToastRef() {
      const unWatch = watchEffect(() => {
        if (!loadingRef.value) return loadingToastIns?.close()
        loadingToastIns = showLoadingToast({ forbidClick: false, duration: 0 })
      })
      onUnmounted(() => {
        unWatch()
        loadingRef.value = false
        loadingToastIns?.close()
      })
    },
    showLoading() {
      if (process.server) return
      times++
      loadingRef.value = true
    },
    hideLoading: () => {
      if (process.server) return
      if (--times) return (times = Math.max(0, times))
      loadingRef.value = false
    },
  }
}

interface AxiosPost<T> {
  <T = any, R = AxiosResponse<T>>(url: string, data?: any, config?: AxiosRequestConfig): Promise<R>
}

interface AxiosGet<T> {
  <T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R>
}

export const useRequest = () => {
  const nuxtApp = useNuxtApp()
  // 此处的函数具体实现在plugins/1.requestPlugin.ts
  return {
    requestGet: (nuxtApp.$requestGet as any).bind(nuxtApp) as AxiosGet<any>,
    requestPost: (nuxtApp.$requestPost as any).bind(nuxtApp) as AxiosPost<any>,
    requestGetNew: async (url: string, params: Record<any, any> = {}, config?: AxiosRequestConfig) => {
      const res = await (nuxtApp.$requestGet as any)(url, { params, ...config })
      return res?.data
    },
    requestPostNew: async (url: string, params: Record<any, any> = {}, config?: AxiosRequestConfig) => {
      const res = await (nuxtApp.$requestPost as any)(url, params, config)
      return res?.data
    },
  }
}
